package org.thunms.demo.test.service;


import java.io.IOException;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.thunms.demo.test.dao.PlaceDao;
import org.thunms.demo.test.entity.Place;

@Service
public class PlaceService {
	private static final Logger logger = LoggerFactory.getLogger(PlaceService.class);
	@Autowired
	private PlaceDao placeDao;

	@Transactional(readOnly = false)
	public void init() {
		
		try {
			//获取解析的资源
			Resource r = new ClassPathResource("org/thunms/demo/test/dao/place.xml");
			//初始化XML文件解析器
			SAXReader saxReader = new SAXReader();
			//获取Document对象
			Document document = saxReader.read(r.getInputStream());
			//获取根节点
			Element root = document.getRootElement();
			List<Element> places=root.elements("place");
			for (Element e : places) {
				if(StringUtils.isNotBlank(e.attributeValue("id"))){
					Place p=new Place();
					p.setId(e.attributeValue("id"));
					p.setPlace(e.attributeValue("place"));
					p.setStatue(e.attributeValue("statue"));
					this.placeDao.save(p);
				}
				
			}

		} catch (DocumentException e) {
			logger.error("XML文档解析过程出现未知异常", e);
		} catch (IOException e) {
			logger.error("读取解析资源出现异常", e);
		}
	}

}
